"use client";
import { setCookie } from "@/libs/cookie";
import { UserEntity } from "@/queries/UserEntity";
import { UserOutlined } from "@ant-design/icons";
import { useApolloClient } from "@apollo/client";
import { Avatar, Button, Dropdown, Layout, Menu } from "antd";
import { usePathname, useRouter } from "next/navigation";
import { PropsWithChildren, useCallback, useMemo } from "react";
const ClientLayout = ({
  children,
  user,
}: PropsWithChildren<{ user: UserEntity }>) => {
  const router = useRouter();
  const pathname = usePathname();
  const client = useApolloClient();
  const menuItems = useMemo(() => {
    return [
      {
        label: "任务列表",
        href: "/",
      },
      {
        label: "班级管理",
        href: "/classes",
      },
      {
        label: "教师列表",
        href: "/teacher",
      },
      {
        label: "学生列表",
        href: "/student",
      },
    ].map((item) => ({ ...item, key: item.href }));
  }, []);
  const onClick = useCallback(({ key }) => {
    router.push(`/admin${key}`);
  }, []);
  const selectedKeys = useMemo(() => {
    const trimmedPath = pathname.replace(/^\/admin/, "") || "/";
    return [trimmedPath];
  }, [pathname]);
  const onLogout = useCallback(() => {
    setCookie("token", "");
    client.clearStore();
    router.push("/");
  }, []);
  const items = useMemo(() => {
    return [
      {
        label: (
          <Button onClick={onLogout} type="text">
            退出登录
          </Button>
        ),
      },
    ].map((item, key) => ({ ...item, key }));
  }, []);
  return (
    <Layout className="h-full">
      <Layout.Header className="px-4">
        <div className="flex justify-between items-center h-full">
          <div className="text-white text-2xl font-bold">Logo</div>
          <div className="flex items-center">
            <Dropdown menu={{ items }} trigger={["hover"]}>
              <Avatar
                size="large"
                icon={<UserOutlined />}
                className="mr-4 cursor-pointer"
              />
            </Dropdown>
            <span className="text-white">{user.account}</span>
          </div>
        </div>
      </Layout.Header>
      <Layout className="h-full">
        <Layout.Sider width={200} className="h-full">
          <Menu
            mode="inline"
            selectedKeys={selectedKeys}
            items={menuItems}
            onClick={onClick}
            theme="dark"
          />
        </Layout.Sider>
        <Layout>
          <Layout.Content>
            <div
              style={{
                height: "calc(100vh - 80px)",
              }}
              className="p-2 m-2 bg-white overflow-y-auto"
            >
              {children}
            </div>
          </Layout.Content>
        </Layout>
      </Layout>
    </Layout>
  );
};
export default ClientLayout;
